# == Schema Information
# Schema version: 8
#
# Table name: users
#
#  id              :integer(11)   not null, primary key
#  login           :string(80)    default(), not null
#  email           :string(60)    default(), not null
#  hashed_password :string(40)    default(), not null
#  display_all     :boolean(1)    not null
#  created_at      :datetime
#  updated_at      :datetime
#

require 'digest/sha1'

class User < ActiveRecord::Base

  validates_length_of :login, :within => 3..40
  validates_uniqueness_of :login
  validates_uniqueness_of :email
  validates_format_of :email, :with => /^[^@]+@.+$/
  validates_format_of :display_all, :with => /true|false/

  validates_presence_of :password, :login, :email
  validates_confirmation_of :password
  validates_length_of :password, :minimum => 5
  validates_length_of :password, :maximum => 40

  attr_accessor :password, :password_confirmation

  validates_confirmation_of :password, :email

  has_many :feeds, :through => :subscriptions
  has_many :subscriptions

  has_many :categories

  def before_create
    self.hashed_password = User.hashed(self.password)
  end

  def after_create
    self.password = nil
  end

  def self.authenticate(login, password)
    find(:first,
         :conditions => ["login = ? and hashed_password = ?",
                         login, hashed(password || "")])
  end

  def has?(feed)
    Subscription.get(self, feed)
  end

  alias get_subscription has?

  def uncategoried
    subscriptions.find_all_by_category_id(-1)
  end

  private
  def self.hashed(password)
    Digest::SHA1::hexdigest(password)
  end

end


